// // 导入express
// const express = require('express')
// const app = express()



// // 导入cors中间件
// const cors = require('cors')
// app.use(cors())
// // 全局解析body参数中间件
// const bodyParser = require('body-parser')
// app.use(bodyParser.json())

// // 配置解析application/x-www-form-urlencoded格式的标点数据中间件
// app.use(express.urlencoded({ extended: true }))

// const userRouter = require('./router/user')
// app.use('/api', userRouter)



// // 调用app.listen 方法,指定端口号启动WEB服务器
// app.listen(3007, () => {
//   var message = '%c服务已启动:127.0.0.1:3007'
//   var style = 'color: red;'
//   console.trace(message, style)
// })

import tsSource from './tsSrc/index.js'
import fs from 'fs'
import path from 'path'
import request from 'request'
import { calcTimeInterval } from './utils/time.js'
import {exec} from 'child_process'
import log from 'single-line-log'
import { setFileName } from './utils/files.js'
 

let moveName = 'test'
let failFile = []
function downloadFileToServer(url, fileName, callback) {
    const filePath = `${path.resolve()}/ts/${fileName}`
    var stream = fs.createWriteStream(filePath);
    request(url, downloadFailHandler)
    .pipe(stream)
    .on('close', callback);
    // 下载失败
    function downloadFailHandler(err){
        if(err){
            failFile.push(fileName)
            console.trace(fileName,'下载失败')
        }
    }
}



function startDownload(){
    const targetSouce = tsSource[moveName]
    console.trace()
    const start = new Date()
    const total = targetSouce.length
    let done = 0
    let index = 0
    let timer = setInterval(() => {
        const filename = `${setFileName(index)}.ts`
        downloadFileToServer(targetSouce[index], filename,()=> {
            done += 1
            const time = calcTimeInterval(start,new Date())
            const { hours, minutes, seconds }=time
            log.stdout(`${filename}下载完成 ${done}/${total}/${failFile.length} (成功/总数/失败)  总用时${hours}:${minutes}:${seconds}   `)
        })
        index += 1
        if (index === targetSouce.length) {
            clearInterval(timer)
            timer=null
            const endTime = new Date()
            // const useTime = startTime - endTime
            console.trace(`下载完成用时${calcTimeInterval(start, endTime)}`)
            downLoadEnd()
        }
    }, 300)
}


function downLoadEnd(){

    try{
        console.trace('使用cmd脚本')
        exec('cd ts && copy /b *.ts new.mp4', (err, stdout, stderr) => {
            console.trace(err)
            console.trace(stdout)
            console.trace(stderr)
            const end = new Date()
            console.trace('总用时', start, end, calcTimeInterval(start, end))
    
        })
    }
    catch{
        console.trace('使用powershell脚本')
        exec(`cd ts && Copy-Item -Path *.ts -Destination mew.mp4`, (err, stdout) => {
            console.trace(err)
            const end = new Date()
            console.trace('总用时', start, end, calcTimeInterval(start, end))
        }) 
    }
    console.trace(failFile)
}


function clearDir(){
    const currentDir = path.resolve()
    const targetDir = `${currentDir}/ts`
    fs.readdir(targetDir,(err,files)=>{
        if(!err){
            // console.trace(files)
            files.forEach((file,index)=>{
                if(index===0){

                    console.trace(typeof file)
                }
            })
        }
        console.trace(`读取${targetDir}文件夹失败`)
    })
}

// clearDir()
console.trace(path.resolve())

function init(){
    // 下载前清空文件夹
    // clearDir()
    // 开始下载
    startDownload()
}


init()


